//
//  SEGPageSizeCustomerCollectionView.m
//  SEGUhomePropertyBaseService
//
//  Created by Clavis on 2018/12/25.
//  Copyright © 2018 刘山. All rights reserved.
//

#import "SEGPageSizeCustomerCollectionView.h"

@interface SEGPageSizeCustomerCollectionView () <UIScrollViewDelegate>

@end

@implementation SEGPageSizeCustomerCollectionView

- (instancetype)initWithFrame:(CGRect)frame collectionViewLayout:(UICollectionViewLayout *)layout {
    self = [super initWithFrame:frame collectionViewLayout:layout];
    if (self) {
        [self setupUIWithLayout:layout];
    }
    return self;
}

- (void)setupUIWithLayout:(UICollectionViewLayout *)layout {
    self.scrollEnabled = NO;
    UICollectionViewFlowLayout *flowLayout = (UICollectionViewFlowLayout *)layout;
    CGFloat width = flowLayout.itemSize.width + flowLayout.minimumLineSpacing;
    UIScrollView *placeholderSV = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, width, 0)];
    placeholderSV.pagingEnabled = YES;
    placeholderSV.delegate = self;
    placeholderSV.showsHorizontalScrollIndicator = NO;
    [placeholderSV addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)]];
    [self addSubview:placeholderSV];
    self.placeholderSV = placeholderSV;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (scrollView == self.placeholderSV) {
        self.contentOffset = scrollView.contentOffset;
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(scrollViewDidEndDecelerating:)]) {
        [self.delegate scrollViewDidEndDecelerating:scrollView];
    }
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if ([view isKindOfClass:[UIButton class]]) {
        return view;
    }
    return self.placeholderSV;
}

- (void)tap:(UITapGestureRecognizer *)tapGR {
    CGPoint point = [tapGR locationInView:self];
    NSIndexPath *indexPath = [self indexPathForItemAtPoint:point];
    if (indexPath && self.delegate && [self.delegate respondsToSelector:@selector(collectionView:didSelectItemAtIndexPath:)]) {
        [self.delegate collectionView:self didSelectItemAtIndexPath:indexPath];
    }
}

@end
